// ChatServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ChatServer.h"
#include "ChatServerDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CChatServerDlg dialog




CChatServerDlg::CChatServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CChatServerDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CChatServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_LOG, m_LogBoard);
}

BEGIN_MESSAGE_MAP(CChatServerDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_SIZE()
	//}}AFX_MSG_MAP
	ON_COMMAND(ID_FILE_EXIT, &CChatServerDlg::OnFileExit)
	ON_COMMAND(ID_FILE_START, &CChatServerDlg::OnFileStart)

	ON_MESSAGE(CHSM_ACCEPT_NEW_CLIENT_GOOD,&CChatServerDlg::OnAcceptClientGood)
	ON_MESSAGE(CHSM_ACCEPT_NEW_CLIENT_FAIL,&CChatServerDlg::OnAcceptClientFail)	
	ON_MESSAGE(CHSM_SERVER_STARTED,&CChatServerDlg::OnServerStarted)
	ON_MESSAGE(CHSM_ACCEPT_SERVER_STOPED,&CChatServerDlg::OnServerStoped)
	ON_MESSAGE(CHSM_CLIENT_DISCONNECT,&CChatServerDlg::OnClientDisconnect)
	ON_MESSAGE(CHSM_RECEIVE_CLIENT_NAME,&CChatServerDlg::OnClientName)
	ON_MESSAGE(CHSM_CLIENT_NAME_DUPLICATE,&CChatServerDlg::OnClientNameDuplicate)

	ON_COMMAND(ID_FILE_STOP, &CChatServerDlg::OnFileStop)
	ON_COMMAND(ID_FILE_SETTINGS, &CChatServerDlg::OnFileSettings)
	ON_COMMAND(ID_TOOLS_ANALYZECHATMESSAGE, &CChatServerDlg::OnToolsAnalyzechatmessage)
	ON_COMMAND(ID_TOOLS_UPDATECLIENTSLIST, &CChatServerDlg::OnToolsUpdateclientslist)
END_MESSAGE_MAP()

BEGIN_EASYSIZE_MAP(CChatServerDlg)
	EASYSIZE(IDC_LIST_LOG, ES_BORDER, ES_BORDER, ES_BORDER, ES_BORDER, 0)
END_EASYSIZE_MAP


// CChatServerDlg message handlers

BOOL CChatServerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	//setup window title
	CString strTitle = _T("Chat Server - Stoped");
	SetWindowText(strTitle);
	INIT_EASYSIZE;

	PostMessage(WM_COMMAND,MAKELONG(ID_FILE_START,0),0);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CChatServerDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CChatServerDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CChatServerDlg::OnCancel()
{
	CChSServer::Instance()->Stop();
	CChSServer::Uninitialize();
	CChSLogWriter::Uninitialize();
	CDialog::OnCancel();
}

void CChatServerDlg::OnFileExit()
{
	CChatServerDlg::OnCancel();
}

void CChatServerDlg::OnFileStart()
{
	CString strLogFileName = _T("ChatLog");
	strLogFileName += CTime::GetCurrentTime().Format(_T("_[%B_%d_%Y][%H_%M_%S].txt"));
	CChSLogWriter::Initialize(strLogFileName);

	CChSSettings* pSettings = CChSSettings::Instance();

	if(TRUE == CChSServer::Instance()->Start(pSettings->HostName(),pSettings->Port()))
	{
		m_LogBoard.AddString(_T("Server started"));
		GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
		GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
		//setup window title
		if(TRUE == CChSServer::Instance()->Started())
		{
			CString strTitle = _T("Chat Server - Started on ");
			strTitle += CChSSettings::Instance()->HostName();
			strTitle.AppendFormat(_T(":%d"),CChSSettings::Instance()->Port());
			SetWindowText(strTitle);
		}
	}
	else
	{
		m_LogBoard.AddString(_T("Server cnat't start"));
		GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
	}
}

void CChatServerDlg::OnFileStop()
{
	CChSLogWriter::Uninitialize();

	CChSServer::Instance()->Stop();
	m_LogBoard.AddString(_T("Server stoped"));
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
	//setup window title
	CString strTitle = _T("Chat Server - Stoped");
	SetWindowText(strTitle);
}

LRESULT  CChatServerDlg::OnAcceptClientGood(WPARAM wParam, LPARAM lParam)
{
	m_LogBoard.AddString(_T("Accept new client - sucessfully"));
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
	return 0;
}

LRESULT  CChatServerDlg::OnAcceptClientFail(WPARAM wParam, LPARAM lParam)
{
	m_LogBoard.AddString(_T("Accept new client - fail"));
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
	return 0;
}

LRESULT  CChatServerDlg::OnServerStarted(WPARAM wParam, LPARAM lParam)
{
	m_LogBoard.AddString(_T("Server started"));
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
	return 0;
}

LRESULT  CChatServerDlg::OnServerStoped(WPARAM wParam, LPARAM lParam)
{
	m_LogBoard.AddString(_T("Server stoped"));
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);
	return 0;
}

LRESULT CChatServerDlg::OnClientNameDuplicate(WPARAM wParam, LPARAM lParam)
{
	CChSClientContext* pClientContext = (CChSClientContext*)lParam;
	pClientContext->ShutDown();
	pClientContext->Close();

	CString strMsg = _T("Client ");
	strMsg += pClientContext->UserName();
	strMsg += _T(" disconnect");
	m_LogBoard.AddString(strMsg);
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);

	CChSServer::Instance()->RemoveClient(pClientContext);

	delete pClientContext;
	pClientContext = NULL;

	return 0;
}

LRESULT  CChatServerDlg::OnClientDisconnect(WPARAM wParam, LPARAM lParam)
{
	CChSClientContext* pClientContext = (CChSClientContext*)lParam;
	pClientContext->ShutDown();
	pClientContext->Close();

	CString strMsg = _T("Client ");
	strMsg += pClientContext->UserName();
	strMsg += _T(" disconnect");
	m_LogBoard.AddString(strMsg);
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);

	CChSServer::Instance()->RemoveClient(pClientContext);

	//send to all users new user name
	CString strUpdateMsg = REMOVE_USER_MESSAGE_PREFIX;
	strUpdateMsg += pClientContext->UserName();
	CChSServer::Instance()->SendToAll(strUpdateMsg);

	delete pClientContext;
	pClientContext = NULL;

	return 0;
}

LRESULT  CChatServerDlg::OnClientName(WPARAM wParam, LPARAM lParam)
{
	CString strTemp((const TCHAR*)lParam);
	CString strMsg = _T("User name - ");
	strMsg += strTemp;
	m_LogBoard.AddString(strMsg);
	GetDlgItem(IDC_LIST_LOG)->SendMessage(WM_VSCROLL, SB_BOTTOM, NULL);

	//send to all users new user name
	CString strUpdateMsg = NEW_USER_MESSAGE_PREFIX;
	strUpdateMsg += strTemp;
	CChSServer::Instance()->SendToAll(strUpdateMsg);

	return 0;
}

void CChatServerDlg::OnFileSettings()
{
	CChSSettingsDlg::SetupSettings();

	if(TRUE == CChSServer::Instance()->Started())
	{
		CString strTitle = _T("Chat Server - Started on ");
		strTitle += CChSSettings::Instance()->HostName();
		strTitle.AppendFormat(_T(":%d"),CChSSettings::Instance()->Port());
		SetWindowText(strTitle);
	}
}

void CChatServerDlg::OnSize(UINT nType, int cx, int cy)
{
	UPDATE_EASYSIZE;
	CDialog::OnSize(nType,cx,cy);
}

void CChatServerDlg::OnToolsAnalyzechatmessage()
{
	if(IDYES == AfxMessageBox(_T("Server will stopped. Are you sure want begin parsing?"),MB_YESNO))
	{
		SendMessage(WM_COMMAND,MAKELONG(ID_FILE_STOP,0),0);
		CChSMessageParserDlg::BeginParsing();
	}
}

void CChatServerDlg::OnToolsUpdateclientslist()
{
	CChSServer::Instance()->UpdateClientsList();
}
